package fun.boomcat.luckyhe.mirai.plugin.botcontrol.command;

import fun.boomcat.luckyhe.mirai.plugin.botcontrol.pojo.Config;
import fun.boomcat.luckyhe.mirai.plugin.botcontrol.util.*;
import kotlin.Unit;
import kotlin.coroutines.Continuation;
import net.mamoe.mirai.Bot;
import net.mamoe.mirai.console.command.CommandManager;
import net.mamoe.mirai.console.command.CommandOwner;
import net.mamoe.mirai.console.command.CommandSender;
import net.mamoe.mirai.console.command.RawCommand;
import net.mamoe.mirai.console.permission.Permission;
import net.mamoe.mirai.contact.ContactList;
import net.mamoe.mirai.contact.Friend;
import net.mamoe.mirai.contact.Group;
import net.mamoe.mirai.event.events.BotInvitedJoinGroupRequestEvent;
import net.mamoe.mirai.event.events.MemberJoinRequestEvent;
import net.mamoe.mirai.event.events.NewFriendRequestEvent;
import net.mamoe.mirai.message.data.MessageChain;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;

import java.io.IOException;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.Set;

public class ControlCommand extends RawCommand {
    public ControlCommand(@NotNull CommandOwner owner, @NotNull String primaryName, @NotNull String[] secondaryNames, @NotNull String usage, @NotNull String description, @NotNull Permission parentPermission, boolean prefixOptional) {
        super(owner, primaryName, secondaryNames, usage, description, parentPermission, prefixOptional);
    }

    @Nullable
    @Override
    public Object onCommand(@NotNull CommandSender commandSender, @NotNull MessageChain messageChain, @NotNull Continuation<? super Unit> continuation) {
        String primaryName = getPrimaryName();
        String[] secondaryNames = getSecondaryNames();
        String commandPrefix = CommandManager.INSTANCE.getCommandPrefix();

        int mcLen = messageChain.toArray().length;
        if (mcLen == 0) {
            commandSender.sendMessage(ControlCommandHelp.commandHelp(primaryName, secondaryNames));
            return null;
        }

        String operation = messageChain.get(0).toString();

        switch (operation.toLowerCase()) {

            case "group":
            case "群":
                onGroup(commandSender, Arrays.copyOfRange(messageChain.toArray(), 1, mcLen), primaryName);
                break;

            case "friend":
            case "好友":
                onFriend(commandSender, Arrays.copyOfRange(messageChain.toArray(), 1, mcLen), primaryName);
                break;

            case "event":
            case "事件":
                onEvent(commandSender, Arrays.copyOfRange(messageChain.toArray(), 1, mcLen), primaryName);
                break;

            case "owner":
            case "主人":
                onOwner(commandSender, Arrays.copyOfRange(messageChain.toArray(), 1, mcLen), primaryName);
                break;

            case "meg":
            case "消息事件群":
                onMeg(commandSender, Arrays.copyOfRange(messageChain.toArray(), 1, mcLen), primaryName);
                break;

            case "fr":
            case "加好友请求":
                onFriendRequest(commandSender, Arrays.copyOfRange(messageChain.toArray(), 1, mcLen), primaryName);
                break;

            case "gr":
            case "加群请求":
                onGroupRequest(commandSender, Arrays.copyOfRange(messageChain.toArray(), 1, mcLen), primaryName);
                break;

            case "igr":
            case "邀请加群请求":
                onInvitedGroupRequest(commandSender, Arrays.copyOfRange(messageChain.toArray(), 1, mcLen), primaryName);
                break;

            case "dc":
            case "直接对话":
                onDirectChatting(commandSender, Arrays.copyOfRange(messageChain.toArray(), 1, mcLen), primaryName);
                break;

            default:
                commandSender.sendMessage("有奇怪的参数，" + commandPrefix + primaryName + "查看帮助");
                break;
        }

        return null;
    }


    private void onGroup(CommandSender commandSender, Object[] args, String primaryName) {
//        指令操作群
        Bot bot = BotUtil.getBotInstance();
        String commandPrefix = CommandManager.INSTANCE.getCommandPrefix();

        int len = args.length;
        if (len == 0) {

            StringBuilder sb = new StringBuilder();

            ContactList<Group> groups;
            try {
                assert bot != null;
                groups = bot.getGroups();
            } catch (Exception e) {
                commandSender.sendMessage("错误：" + e.toString());
                return;
            }

            sb.append(BotUtil.getGroupsStr(groups));
            sb.append(commandPrefix).append(primaryName).append(" group <群号>    查看某群相关内容");
            BotUtil.pageSender(commandSender, sb.toString());
            return;
        }

        long groupId;
        try {
            groupId = Long.parseLong(args[0].toString());
        } catch (Exception e) {
            commandSender.sendMessage("错误：" + e.toString());
            return;
        }

        Group group = bot.getGroup(groupId);
        if (group == null) {
            commandSender.sendMessage("群列表中没有该群");
            return;
        }

        if (len == 1) {//                只传入群号时
            args = Arrays.copyOfRange(args, 1, len);
            if (args.length == 0) {
                commandSender.sendMessage(BotUtil.getGroupMulLineStr(group, primaryName));
            }
        } else {//                来到这参数长度必为2，传入参数至少为1
            GroupOperation.groupOperation(commandSender, Arrays.copyOfRange(args, 1, len), group, primaryName);
        }

    }

    private void onFriend(CommandSender commandSender, Object[] args, String primaryName) {
//        好友相关操作
        int len = args.length;
        Bot bot = BotUtil.getBotInstance();
        String commandPrefix = CommandManager.INSTANCE.getCommandPrefix();

        if (len == 0) {
            StringBuilder sb = new StringBuilder();
            ContactList<Friend> friends;

            try {
                assert bot != null;
                friends = bot.getFriends();
            } catch (Exception e) {
                commandSender.sendMessage("错误：" + e.toString());
                return;
            }

            sb.append(BotUtil.getFriendsStr(friends));
            sb.append(commandPrefix).append(primaryName).append(" friend <好友QQ>    查看该好友相关内容");

            BotUtil.pageSender(commandSender, sb.toString());
            return;
        }

        long friendId;
        try {
            friendId = Long.parseLong(args[0].toString());
        } catch (Exception e) {
            commandSender.sendMessage("错误：" + e.toString());
            return;
        }

        Friend friend = bot.getFriend(friendId);
        if (friend == null) {
            commandSender.sendMessage("好友列表中没有该好友");
            return;
        }

        if (len == 1) {
            args = Arrays.copyOfRange(args, 1, len);
            if (args.length == 0) {
                commandSender.sendMessage(BotUtil.getFriendMulLineStr(friend, primaryName));
            }
        } else {
            FriendOperation.friendOperation(commandSender, Arrays.copyOfRange(args, 1, len), friend, primaryName);
        }
    }

    private void onEvent(CommandSender commandSender, Object[] args, String primaryName) {
//        与事件相关操作
        int len = args.length;
        String commandPrefix = CommandManager.INSTANCE.getCommandPrefix();

        if (len == 0) {
            Config config;
            try {
                config = ConfigUtil.getConfig();
            } catch (Exception e) {
                commandSender.sendMessage("错误：" + e.toString());
                return;
            }

            StringBuilder sb = new StringBuilder();
            sb.append("事件：");

            Set<Map.Entry<String, Boolean>> entries = config.getEvents().entrySet();

            commandSender.sendMessage(BotUtil.getEventStateMulStr(entries, primaryName));
        } else {
            EventOperation.eventOperation(commandSender, Arrays.copyOfRange(args, 0, len));
        }

    }

    private void onOwner(CommandSender commandSender, Object[] args, String primaryName) {
//        主人QQ相关
        int len = args.length;
        Config config;
        String commandPrefix = CommandManager.INSTANCE.getCommandPrefix();

        try {
            config = ConfigUtil.getConfig();
        } catch (IOException e) {
            commandSender.sendMessage("错误：" + e.toString());
            return;
        }

        if (len == 0) {
            commandSender.sendMessage("当前主人QQ：" + config.getOwnerQQ() + "\n" +
                    "使用" + commandPrefix + primaryName + " owner <新QQ>    设置新主人QQ（消息通知对象，必须为好友）");
            return;
        }

        OwnerQQOperation.ownerQQOperation(commandSender, args);
    }

    private void onMeg(CommandSender commandSender, Object[] args, String primaryName) {
//        消息事件群相关
        int len = args.length;
        Config config;
        try {
            config = ConfigUtil.getConfig();
        } catch (IOException e) {
            commandSender.sendMessage("错误：" + e.toString());
            return;
        }

        if (len == 0) {
            commandSender.sendMessage(BotUtil.getMessageEventGroupsMulStr(
                    config.getGroupsForGroupMessageEvent(),
                    primaryName
            ));

        } else {
            MessageEventGroupOperation.megOperation(commandSender, args, primaryName);
        }
    }

    private void onFriendRequest(CommandSender commandSender, Object[] args, String primaryName) {
//        加好友请求相关
        String commandPrefix = CommandManager.INSTANCE.getCommandPrefix();
        int len = args.length;

        if (len == 0) {
            List<NewFriendRequestEvent> events = NewFriendRequestEventUtil.getEvents();
            commandSender.sendMessage(BotUtil.getFriendRequestsMulStr(events, primaryName));

        } else {
            NewFriendRequestOperation.newFriendRequestOperation(
                    commandSender,
                    args,
                    primaryName
            );
        }
    }

    private void onGroupRequest(CommandSender commandSender, Object[] args, String primaryName) {
//        加群请求相关
        String commandPrefix = CommandManager.INSTANCE.getCommandPrefix();
        int len = args.length;

        if (len == 0) {
            List<MemberJoinRequestEvent> events = MemberJoinRequestEventUtil.getEvents();
            commandSender.sendMessage(BotUtil.getMemberJoinRequestMulStr(events, primaryName));
        } else {
            MemberJoinRequestOperation.memberJoinRequestOperation(
                    commandSender,
                    args,
                    primaryName
            );
        }
    }

    private void onInvitedGroupRequest(CommandSender commandSender, Object[] args, String primaryName) {
//        Bot被邀请加群请求相关
        String commandPrefix = CommandManager.INSTANCE.getCommandPrefix();
        int len = args.length;

        if (len == 0) {
            List<BotInvitedJoinGroupRequestEvent> events = BotInvitedJoinGroupRequestEventUtil.getEvents();
            commandSender.sendMessage(BotUtil.getBotInvitedJoinGroupRequest(events, primaryName));
        } else {
            BotInvitedJoinGroupRequestOperation.botInvitedJoinGroupRequestOperation(
                    commandSender,
                    args,
                    primaryName
            );
        }
    }

    public void onDirectChatting(CommandSender commandSender, Object[] args, String primaryName) {
//        与直接对话操作相关
        int len = args.length;

        if (len == 0) {
            commandSender.sendMessage(ControlCommandHelp.directChattingHelp(primaryName));
            commandSender.sendMessage("当前设置：\n" + "QQ：" + CurrentChattingUtil.getQq() +
                    "\n群号：" + CurrentChattingUtil.getGroupId());
        } else {
            DirectChattingOperation.directChattingOperation(commandSender, args, primaryName);
        }
    }
}
